package kyo;

import java.util.Scanner;

public class CommonMenu<I, D> extends Menu<I, D> {
    // 退出提示信息
    private I quitMes = null;
    //通用获取输入对象
    private static Scanner sc = new Scanner(System.in);

    public CommonMenu() {
        this(null, null, null);
    }

    public CommonMenu(I title) {
        this(title, null, null);
    }

    public CommonMenu(I title, I quitMes) {
        this(title, quitMes, null, null);
    }

    public CommonMenu(I title, ItemRun iRun) {
        this(title, iRun, null);
    }

    public CommonMenu(ItemRun iRun) {
        this(null, iRun, null);
    }

    public CommonMenu(ItemRun iRun, D itemData) {
        this(null, iRun, itemData);
    }

    public CommonMenu(I title, ItemRun iRun, D itemData) {
        set(title, iRun, itemData);
    }

    public CommonMenu(I title, I quitMes, ItemRun iRun, D itemData) {
        set(title, quitMes, iRun, itemData);
    }

    public CommonMenu<I, D> set(I title, I quitMes, ItemRun iRun, D itemData) {
        setTitle(title);
        setQuitMes(quitMes);
        setRun(iRun);
        setData(itemData);
        return this;
    }

    public CommonMenu<I, D> setQuitMes(I quitMes) {
        this.quitMes = quitMes;
        return this;
    }

    public CommonMenu<I, D> setQuitItem(I info) {
        this.add(info, new ItemRun() {
            public <I, D> RunState run(Item<I, D> Item) {
                return RunState.RETURN;
            }
        });
        return this;
    }

    private void showPrefix() {
        int menuLevel = getLevel();
        for (int i = 0; i < menuLevel; ++i) {
            System.out.print("\t");
        }
    }

    @Override
    public void showItem(int index, I itemInfo) {
        showPrefix();
        if (index <= 0) {
            System.out.println(itemInfo.toString());
        } else {
            System.out.println(String.valueOf(index)
                                    + '.' + itemInfo.toString());
        }
    }

    public Item<I, D> getItem() {
        int n = 0;
        int size = getSize();
        showPrefix();
        System.out.printf("请输入[1 - %d]: ", size);
        n = sc.nextInt() - 1;
        if (n < 0 || n >= size)
            return null;
        return get(n);
    }

    /**
     * 运行菜单功能.
     *
     * 重写父类抽象方法. 实现通用文本菜单功能. 可以自定义菜单输出/输入格式
     *
     * @see Menu#run()
     */
    public boolean run() {
        Item<I, D> item = null;
        RunState state = null;

        if (quitMes != null) {
            setQuitItem(quitMes);
        }
        while (true) {
            showList();
            item = getItem();

            if (item == null)
                continue;

            if (item.isSubMenu()) {
                if (item.getSubMenu().run())
                    return true;
            } else {
                state = item.run();
                if (state != RunState.RUNNING)
                    break;
            }
        }

        return state == RunState.QUIT ? true : false;
    }
}
